package com.guoliang.eduService.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guoliang.commonUtils.CommonResult;
import com.guoliang.commonUtils.JwtUtils;
import com.guoliang.commonUtils.entity.UcenterMember;
import com.guoliang.eduService.entity.EduComment;
import com.guoliang.eduService.service.EduCommentService;
import com.guoliang.eduService.service.UcenterMemberClient;
import com.guoliang.service.exceptionHandler.MyException;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author leo
 * @since 2023-01-18
 */
@RestController
@RequestMapping("/eduService/eduComment")
public class EduCommentController {
    @Autowired
    EduCommentService commentService;
    @Resource
    UcenterMemberClient memberClient;
    @ApiOperation("获取评论分页列表")
   @GetMapping("/get/{page}/{limit}")
    public CommonResult getComment(@PathVariable("page") Long page,@PathVariable("limit") Long limit
    ,@RequestParam String courseId,HttpServletRequest request){
        System.out.println(request.getRequestURL());
        Page<EduComment> pageParam=new Page<>(page,limit);
       QueryWrapper<EduComment> wrapper=new QueryWrapper<>();
       wrapper.eq("course_id",courseId);
       wrapper.orderByDesc("gmt_create");
       commentService.page(pageParam,wrapper);
       List<EduComment> commentList = pageParam.getRecords();
       Map<String, Object> map = new HashMap<>();
       map.put("items", commentList);
       map.put("current", pageParam.getCurrent());
       map.put("pages", pageParam.getPages());
       map.put("size", pageParam.getSize());
       map.put("total", pageParam.getTotal());
       map.put("hasNext", pageParam.hasNext());
       map.put("hasPrevious", pageParam.hasPrevious());
        return CommonResult.ok().date(map);
   }
    @ApiOperation("添加评论")
    @PostMapping
    public CommonResult addComment(@RequestBody EduComment comment, HttpServletRequest request){
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)){
            throw new MyException(20001,"请先登录");
        }
        UcenterMember member = memberClient.getMember(memberId);
        comment.setMemberId(memberId);
        comment.setNickname(member.getNickname());
        comment.setAvatar(member.getAvatar());
        commentService.save(comment);
        return CommonResult.ok();
    }

}
